package top.kaoshanji.r1ch04b;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/**
 * 代码清单-r1ch04b-110页a：BeanLifeCycle
 * @author kaoshanji
 * ^_^
 * create time 2025/5/5 16:43
 */
public class BeanLifeCycle {

    private static void lifeCycleInBeanFactory() {

        // 装载配置文件并启动容器
        Resource res = new ClassPathResource("r1ch04b/beanfactory-car-beans.xml");

        BeanFactory bf = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader((DefaultListableBeanFactory)bf);
        reader.loadBeanDefinitions(res);

        // 向容器注册 MyBeanPostProcessor 后处理器
        ((ConfigurableBeanFactory)bf).addBeanPostProcessor(new MyBeanPostProcessor());

        // 向容器注册 MyInstantiationAwareBeanPostProcessor 后处理器
        ((ConfigurableBeanFactory)bf).addBeanPostProcessor(new MyInstantiationAwareBeanPostProcessor());


        // 第一次从容器中获 car ，将触发容器实例化该Bean，这将引发Bean生命周期方法的调用
        Car car1 = (Car) bf.getBean("car");
        car1.introduce();
        car1.setColor("红色");

        // 第二次从容器中获取 car ，直接从缓冲池中获取
        Car car2 = (Car)bf.getBean("car");

        // 查看 car1 和 car2 是否指向同一引用
        System.out.println("car1==car2：" + (car1 == car2));

        // 关闭容器
        ((DefaultListableBeanFactory)bf).destroySingletons();

    }

    public static void main(String[] args) {
        lifeCycleInBeanFactory();
    }

}
